package standart;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;

import org.xml.sax.SAXException;

public class Server {
	private int port;
	public Server(int port) {
		this.port = port;
	}

	public void RunServer() throws IOException, SAXException,
			ParserConfigurationException {
		while (true) {
			try (ServerSocket ss = new ServerSocket(port)) {

				Socket socket = ss.accept();

				InputStream sinClient = socket.getInputStream();
				OutputStream soutClient = socket.getOutputStream();

				DataInputStream inClient = new DataInputStream(sinClient);
				DataOutputStream outClient = new DataOutputStream(soutClient);

				String line = inClient.readUTF();
				System.out.println("Client send to the server: " + line);

				List list = new XMLParse()
						.ParseForConnection("configFiles\\config.xml");

				try (Socket socketCertCenter = ConnectToCertCenter(
						(String) list.get(0),
						Integer.valueOf((String) list.get(1)))) {

					InputStream sinCertCenter = socketCertCenter
							.getInputStream();
					OutputStream soutCertCenter = socketCertCenter
							.getOutputStream();

					DataInputStream inCertCenter = new DataInputStream(
							sinCertCenter);
					DataOutputStream outCertCenter = new DataOutputStream(
							soutCertCenter);

					outCertCenter.writeUTF(line);
					outCertCenter.flush();

					line = inCertCenter.readUTF();
					System.out
							.println("Certification center send to the server:"
									+ "(1 is ok,-1 is bad) " + line);

					if (line.equals("1")) {
						outClient.writeUTF("200OK");
						outClient.flush();
						
						String encrMessage = inClient.readUTF();
						char[] chArray = encrMessage.toCharArray();
						
						char[] temp =new char[1000];
						for(int i=0;i<chArray.length;i++){
							temp[i]= (char) (chArray[i]+17);
						}
						outClient.writeUTF(new String(temp));
						outClient.flush();
							
						}
						
					 else {
						outClient.writeUTF("404BAD");
						outClient.flush();
					}

				} catch (Exception ex) {
				}
				finally{
					ss.close();
					
				}
			}
		}

	}

	public Socket ConnectToCertCenter(String ipCertCenter, int port)
			throws UnknownHostException, IOException {
		return (new Socket(ipCertCenter, port));

	}
}
